import type { Ref } from "vue";
import { updateRobotControl } from "../../api/robotRemoteControl";
import { ElMessage } from "element-plus";
interface Options {
  robotCode: Ref<number>;
  ledValue: Ref<boolean>;
  tailRodValueOne: Ref<boolean>;
  tailRodValue: Ref<boolean>;
  direction: Ref<number>;
}
export default (options: Options) => {
  const { robotCode, ledValue, tailRodValueOne, tailRodValue, direction } =
    options;
  let timer: any;
  let isLed: any;
  /**
   * 处理手柄前进后退
   * @param type
   * @param val
   * @param isDirection 判断是否前进左转/右转
   */
  async function handleGamepadControl(type: any, val: any, isDirection: any) {
    clearTimeout(timer);
    isLed = false;
    isSelectRobot();
    let data;
    if (!isDirection) {
      data = {
        type: "navigation",
        robot: robotCode.value,
        X: tailRodValueOne.value ? "1" : "0",
        Y: tailRodValue.value ? "1" : "0",
        V: ledValue.value ? "0" : "1",
        [type]: val,
      };
    } else {
      data = {
        type: "navigation",
        robot: robotCode.value,
        X: tailRodValueOne.value ? "1" : "0",
        Y: tailRodValue.value ? "1" : "0",
        V: ledValue.value ? "0" : "1",
        [type]: val,
        L: Math.abs(val),
      };
    }
    await updateRobotControl(data);
    timer = setTimeout(async () => {
      if (direction.value !== 0) {
        handleGamepadControl(type, val, isDirection);
      } else {
        isLed = ledValue.value;
        if (isLed) {
          toggleLedStartAway();
        }
      }
    }, 400);
  }
  /**
   * led灯
   */
  function toggleLedStartAway() {
    clearTimeout(timer);
    isSelectRobot();
    ledValue.value = true;
    handleBtnRequest();
    isLed = ledValue.value;
    timer = setTimeout(async () => {
      if (isLed === true) {
        toggleLedStartAway();
      }
    }, 400);
  }
  function toggleLedCloseAway() {
    clearTimeout(timer);
    isSelectRobot();
    ledValue.value = false;
    handleBtnRequest();
  }

  /**
   * 舵机
   */
  function toggleGear1Away() {
    isSelectRobot();
    tailRodValueOne.value = !tailRodValueOne.value;
    handleBtnRequest();
  }
  function toggleGear2Away() {
    isSelectRobot();
    tailRodValue.value = !tailRodValue.value;
    handleBtnRequest();
  }
  function isSelectRobot() {
    if (!robotCode.value) {
      return ElMessage({ type: "warning", message: "请选择机器人" });
    }
  }
  async function handleBtnRequest() {
    const data = {
      robot: robotCode.value,
      type: "navigation",
      V: ledValue.value ? "0" : "1",
      X: tailRodValueOne.value ? "1" : "0",
      Y: tailRodValue.value ? "1" : "0",
    };
    await updateRobotControl(data);
  }

  return {
    handleGamepadControl,
    toggleLedStartAway,
    toggleLedCloseAway,
    toggleGear1Away,
    toggleGear2Away,
  };
};
